package aspect;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import pojo.User;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 切面类
 */
@Aspect
@Component
public class UserLogger {
    private static final Logger logger= Logger.getLogger(UserLogger.class);

    @Pointcut("execution(* controller.*.welcome(..))")
    public void pointcut1(){}

    @Pointcut("execution(* controller.*.addAndSaveUser(..))")
    public void pointcut2() {}


    @AfterReturning("pointcut1()")
    public void afterReturning1(JoinPoint jp) {
        Object[] args = jp.getArgs();
        HttpSession session=(HttpSession) args[0];
        User user = (User) session.getAttribute("user");
        Date date=new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentTime = sdf.format(date);
        logger.info(currentTime+",用户"+user.getUserName()+"登录成功");
        //System.out.println(currentTime+",用户"+user.getUserName()+"登录成功");
    }

    @AfterReturning("pointcut2()")
    public void afterReturning2(JoinPoint jp){
        Object[] args = jp.getArgs();
        User addUser=(User) args[0];
        HttpSession session=(HttpSession) args[1];
        User user = (User) session.getAttribute("user");
        Date date=new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentTime = sdf.format(date);
        //System.out.println(currentTime+",用户"+addUser.getUserName()+"由"+user.getUserName()+"添加成功");
        logger.info(currentTime+",用户"+addUser.getUserName()+"由"+user.getUserName()+"添加成功");
    }
}
